package com.example.web1012.Interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @projectName: web10-12
 * @package: com.example.web1012.Interceptor
 * @className: LogInterceptor
 * @author: Berry Peng
 * @description: 登录拦截器
 * @date: 2022/10/23 16:09
 * @version: 1.0
 */
public class LogInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
        if(!Objects.equals(request.getRequestURI(), "/login.html") && !request.getRequestURI().equals("/login/userLogin")){
            if(request.getSession().getAttribute("isLogin") != null && (boolean)request.getSession().getAttribute("isLogin")){
                System.out.println("OK");
                return true;
            }else {
                response.sendRedirect("/login.html");
                return false;
            }
        }
        
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
        System.out.println("\n-------- LogInterception.postHandle --- ");
        System.out.println("Request URL: " + request.getRequestURL());
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("\n-------- LogInterception.afterCompletion --- ");
    }
}
